package com.xdwanj.dao;

import com.xdwanj.util.PageBean;
import com.xdwanj.util.JdbcUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.ArrayList;
import java.util.List;

public class BaseDao {

    private JdbcTemplate jdbcTemplate;

    public BaseDao() {
        jdbcTemplate = JdbcUtil.getJdbcTemplate();
    }

    /**
     * 获得 JdbcTemplate 对象
     * @return
     */
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    /**
     * 返回分页对象
     *
     * @param sql       查询sql
     * @param queryArgs 查询参数
     * @param rowMapper dto mapper
     * @param countSql  总量sql
     * @param countArgs 总量参数
     * @param page      当前页
     * @param size      每页大小
     * @param <T>       dto
     * @return 分页对象
     */
    public <T> PageBean getCustomerPageDto(String sql, Object[] queryArgs, RowMapper<T> rowMapper, String countSql, Object[] countArgs, int page, int size) {

        if (page <= 0) {
            throw new RuntimeException("当前页数必须大于1");
        }
        if (size <= 0) {
            throw new RuntimeException("每页大小必须大于1");
        }
        //总共数量
        int totalSize = jdbcTemplate.queryForObject(countSql, countArgs, Integer.class);
        if (totalSize == 0) {
            return new PageBean().setContent(new ArrayList())
                    .setElementTotalSize(0)
                    .setPage(0)
                    .setSize(0)
                    .setTotalPage(0)
                    .setTotalSize(0);
        }
        //总页数
        int totalPage = totalSize % size == 0 ? totalSize / size : totalSize / size + 1;
        //开始位置
        int offset = (page - 1) * size;
        //结束位置
        int limit = offset + size;
        sql = sql + " limit " + limit + " offset " + offset;
        List<T> content = jdbcTemplate.query(sql, queryArgs, rowMapper);
        return new PageBean().setContent(content)
                .setElementTotalSize(content.size())
                .setPage(0)
                .setSize(0)
                .setTotalPage(0)
                .setTotalSize(0);
    }

}
